import { currentDates, time } from '../../utils/util'
import Pay from '../../utils/pay'
const app = getApp()
Page({
  data: {
    imgurl: app.globalData.imgurl,
    num: 1,
    pay_method: 1,
    // 提交节流阀
    flag: false,
  },
  onShow() {
    this.setData({
      flag: false,
    })
  },
  //选择宝宝人数
  onChangenum({ detail }) {
    this.setData({
      num: detail,
    })
  },
  // 选择支付方式
  _success({ detail }) {
    this.setData({
      pay_method: detail,
    })
  },
  // 点击支付
  async submit() {
    console.log('支付')
    const { gss_id, num, pay_method } = this.data
    this.setData({
      flag: true,
    })
    let { code, data, msg } = await wx.requestAsync({
      url: '/game/spell/create',
      data: {
        gss_id,
        pay_method,
        num,
      },
    })
    if (code == 0) {
      if (!data) {
        return wx.showToast({
          title: '预约成功',
          icon: 'none',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              this.setData({
                flag: false,
              })
              wx.redirectTo({
                url: '/pages/appointment/appointment',
              })
            }, 1000)
          },
        })
      } else {
        // 调用微信支付接口
        let flag = await Pay({ ...data }, data)
        if (flag || !flag) {
          wx.redirectTo({
            url: '/pages/appointment/appointment',
          })
        }
      }
    } else {
      this.setData({
        flag: false,
      })
    }
  },
  onLoad({ gss_id }) {
    this._getData(gss_id)
  },
  async _getData(gss_id) {
    let { code, data } = await wx.requestAsync({
      url: '/game/spell/detail',
      data: {
        gss_id,
      },
    })
    if (code == 0) {
      let date = (data.begin_at =
        currentDates(data.begin_at * 1000) +
        ' ' +
        time(data.begin_at) +
        '-' +
        time(data.end_at))
      this.setData({
        date,
      })
      this.setData(data)
    }
  },
})
